package com.misc.tunewsreader;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.TextView;

public class ReplyAdapter extends ArrayAdapter<NNTPPost> implements Filterable {

    private List<NNTPPost> items;
    private int layout_id;
    private Context context;
    private long marked = -1;

    public ReplyAdapter(Context context, int textViewResourceId,
	    List<NNTPPost> threads) {
	super(context, textViewResourceId, threads);
	this.items = threads;
	this.context = context;
	this.layout_id = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
	View view = convertView;
	if (view == null) {
	    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
	    view = inflater.inflate(layout_id, parent, false);
	}
	NNTPPost tinfo = items.get(position);
	if (tinfo != null) {
	    view.setPadding((tinfo.getLayer() + 1) * 32, 0, 0, 0);
	    TextView title_text = (TextView) view
		    .findViewById(R.id.reply_subject);
	    TextView author_text = (TextView) view
		    .findViewById(R.id.reply_author);
	    TextView post_id = (TextView) view.findViewById(R.id.replyid);
	    TextView date_text = (TextView) view.findViewById(R.id.reply_date);

	    // highlight active post and mark as read
	    if (tinfo.getHeader().getThreadId() == marked) {
		if (!tinfo.isRead())
		    tinfo.setRead(true);
		view.setBackgroundResource(R.drawable.selected_post);
	    } else {
		// view.setBackgroundColor(Color.WHITE);
		view.setBackgroundResource(0);
	    }

	    // set text
	    if (title_text != null) {
		title_text.setText(tinfo.getHeader().getSubject());
		if (!tinfo.isRead())
		    title_text.setTypeface(null, Typeface.BOLD);
		else
		    title_text.setTypeface(null, Typeface.NORMAL);
	    }
	    if (author_text != null) {
		author_text.setText(tinfo.getHeader().getAuthorName());
	    }
	    if (post_id != null) {
		post_id.setText("" + tinfo.getHeader().getThreadId());
	    }
	    if (date_text != null) {
		date_text.setText(tinfo.getHeader().getDate());
	    }

	}
	return view;
    }

    public NNTPPost getItem(int position) {
	return items.get(position);
    }

    public int getPosition(NNTPPost item) {
	return items.indexOf(item);
    }

    public long getItemId(int position) {
	return position;
    }

    public int getCount() {
	return items.size();
    }

    public void setMarked(long id) {
	marked = id;
    }
}
